$(document).ready(function(){
	var bannerHeight = $(".banner").height();
	var uri = "http://116.62.5.177:8089/ps_mall/";
	// var uri1 = "http://116.62.5.177:8080/PSmall/";
	document.body.addEventListener('touchstart', function () {}); 
	var timer = null;
	var nFromNum = 0; // 主题开始页面
	var nToNum = 20;   // 主题结束页面
	var cityClicked = false;  //  判断是否加载过城市数据，如果以及加载过，不需要
	var publicKey = null;// md5

	function GetQueryString(name) {
	     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	     var r = window.location.search.substr(1).match(reg);
	     if(r!=null)return  unescape(r[2]); return null;
	}

	// $(document).on("pageInit", "#page-index", function(e, pageId, $page) {
		// 城市定位
		function cityLoction() {
			$.ajax({
				type : "POST",
				url : 'http://api.map.baidu.com/location/ip?ak=Y75nQRftejAP1Bni2WkQ2C1eKvKXNrKc&coor=bd09ll',
				contentType:"application/json;charset=UTF-8",  //发送至服务器的类型
				dataType : "jsonp",     //预期服务器返回类型
				success: function(data){
					console.log(data);
					if(data.status == 0) {
						$('.locat,.posi-loca strong').html(data.content.address_detail.city.substring(0,2));
					} else {
						$.alert(data.message);
					}
				}

		  	});
		}
		cityLoction();
		// 首页 导航分页固定
		$(document).on("pageInit", function() {
		  	$('.buttons-tab').fixedTab({offset:50});
		});
		// 点击定位显示城市列表
		$(document).on("click",".locat", function() {
			if(cityClicked == false) {
			 	$.ajax({
					type : "GET",
					url : uri + "common/citys",
					contentType:"application/json;charset=UTF-8",  //发送至服务器的类型
					dataType : "json",     //预期服务器返回类型
					success: function(data){
						console.log(data);
						if(data.code == 0) {
							var list_tpl = $('#list_tpl2').html();
							var content = doT.template(list_tpl);
							$(".content-city .city-block").html(content(data.object)); 
							cityClicked = true;
						} else {
							$.alert(data.messages)
						}
					}

			  	});
			}
			$.popup('.popup-city');
		})
		console.log(localStorage.getItem("arrCity"));
		var arrCity = [];
		var showKeyTheme1 = "";  	// 户型关键字
		var showKeyTheme2 = ""; 	// 风格关键字
		//点击城市获取相应的城市名称
		$(document).on('click', '.city-block li .item-content', function(event) {
			$(".locat").html($(this).text());
			arrCity.unshift($(this).text());
			if(arrCity.length >= 6) {
				arrCity.pop();
			}
			localStorage.setItem('arrCity', arrCity);
			console.log(arrCity);
			$.closeModal('.popup-city');
			// 记录城市名称 不操过六个
		});
		// 点击筛选
		$(document).on('click', '.seach', function(event) {
			$.popup('.popup-style');
		});

		// 1960.5 
		// 通讯录效果
		$(document).on('click','.zm li', function(event) {
			var s = $(this).index();
			// if(dom.length > 0) {
			var h = eachHeight();
			$('.content-city').scrollTop(h[s]);
			// }
			console.log();
			
		});
			
		function eachHeight() {
			var arrHeigth = [];
			var headHeight = $('.con-header').height();
			var thisHeigth = 0;
			arrHeigth.push(headHeight);
			$(".content-city .city-block .list-group").each(function(index, el) {
				thisHeigth = parseInt($(this).height()) + arrHeigth[index];
				// thisHeigth = thisHeigth + headHeight;
				arrHeigth.push(thisHeigth);
			});
			console.log(arrHeigth);
			return arrHeigth;
		}
		function listTopic(nFromNum, nToNum) {
			$("#tab1").html("<div class='data-tip'>加载数据……</div>");
			var jsonData  = {
		        "nFrom" : nFromNum ,
		        "nTo" : nToNum,
		    };
		    $.ajax({
		        type: 'get',
		        url: uri+'/topic/list',
		        contentType:'application/json;charset=utf-8',//指定为json类型
		        //数据格式是json串，商品信息
		        //data:JSON.stringify(jsonData),
		        data: jsonData,
		        cache: true,
		        success:function(data){//返回json结果
		        	console.log(data);
		            if(data.code == 0) {
						var list_tpl = $('#list_tpl1').html();
						var content = doT.template(list_tpl);
						$("#tab1").html(content(data.object));          	
		            } else {
		            	$.alert(data.message);
		            }
		        } 
		    });
		}
		listTopic(nFromNum, nToNum);

		// 筛选
		function screen() {
		    $.ajax({
		        type: 'GET',
		        cache: true,
		        url: uri+'common/style',
		        contentType:'application/json;charset=utf-8',//指定为json类型
		        //数据格式是json串，商品信息
		        // data:JSON.stringify(jsonData),
		        success:function(data){//返回json结果
		        	console.log(data);
					var list_tpl = $('#list_tpl4').html();
					var content = doT.template(list_tpl);
					$(".con-header2 .row").html(content(data.object));    
		            // alert(data.code + '  ' + data.message);
		            // $('#returnmsg').val(JSON.stringify(data.object));
		        }
		    });
		}screen()

		// 获取户型
		function getDoorType() {
		    $.ajax({
		        type: 'GET',
		        cache: true,
		        url: uri+'common/huxing',
		        contentType:'application/json;charset=utf-8',//指定为json类型
		        //数据格式是json串，商品信息
		        // data:JSON.stringify(jsonData),
		        success:function(data){//返回json结果
		        	console.log(data);
					var list_tpl = $('#list_tpl4').html();
					var content = doT.template(list_tpl);
					$(".con-header1 .row").html(content(data.object));    
		        }
		    });
		}getDoorType();

		// 筛选显示主题列表


		$(document).on('click', '.con-header1 .row div', function(event) {
			$(this).addClass('sel').siblings('div').removeClass("sel");
			showKeyTheme1 = $(this).text();
			console.log(showKeyTheme1);
		});
		$(document).on('click', '.con-header2 .row div', function(event) {
			$(this).addClass('sel').siblings('div').removeClass("sel");
			showKeyTheme2 = $(this).text();
			console.log(showKeyTheme2);
		});
		// 重置
		$(document).on('click', '.con-ci span:nth-child(1)', function(event) {
			$(".con-header .row div").removeClass("sel");
		});
		// 选择确认
		$(document).on('click', '.con-ci span:nth-child(2)', function(event) {
			var jsonData  = {
			 	"houseName": "",
		        "city" : $(".locat").html(), //城市
		        "style": showKeyTheme2,//装修风格
		        "huxing": showKeyTheme1 // 三室一厅
		        // "loupan":  2;// 楼盘编号 
		    };
			$.ajax({
		        type: 'POST',
		        url: uri+'topic/search',
		        contentType:'application/json;charset=utf-8',//指定为json类型
		        //数据格式是json串，商品信息
		        data:JSON.stringify(jsonData),
		        success:function(data){//返回json结果
		        	console.log(data);
					var list_tpl = $('#list_tpl1').html();
					var content = doT.template(list_tpl);
					$("#tab1").html(content(data.object));
					$.closeModal('.popup-style');
		        }
		    });
		});
	// });
	$(document).on('click', '#tab1 dl a', function(event) {
		var themeId = $(this).attr("id");
		$.router.load('subject_detail.html?id='+themeId);
		themeDetail(themeId);
	});
	$(document).on('click', '.collection', function(event) {
		var topicId = $(this).attr("id");
		collectionTheme(topicId);
	});
	var themeIds = GetQueryString("id");
	if(themeIds != undefined) {
		themeDetail(themeIds)
	}

	// 主题详情
	function themeDetail(themeId) {

		$.ajax({
	        type: 'GET',
	        cache: true,
	        url: uri+'topic/fetch?id='+themeId,
	        contentType:'application/json;charset=utf-8',//指定为json类型
	        //数据格式是json串，商品信息
	        success:function(data){//返回json结果
	        	console.log(data);
				var list_tpl = $('#list_tpl5').html();
				var content = doT.template(list_tpl);
				$(".detail-tab .tab").html(content(data.object));
				themeDetailAll(data.object.id);
	        }
	    });
	}

	function themeDetailAll(themeId) {
		$("#dataTip").html("数据加载中……");
		$.ajax({
	        type: 'GET',
	        cache: true,
	        url: uri+'topic/view?id='+themeId,
	        contentType:'application/json;charset=utf-8',//指定为json类型
	        //数据格式是json串，商品信息
	        success:function(data){//返回json结果
	        	console.log(data);
	        	if(data.object.zones.length == 0) {
	        		$("#dataTip").html("暂无信息");
	        	} else {
					var list_tpl = $('#list_tpl6').html();
					var content = doT.template(list_tpl);
					$("#dataTip").html(content(data.object.zones));
	        	}
	        }
	    });
	}

	function collectionTheme(topicId) {
		var thisDom = $(this);
		$.ajax({
            type:'get',
            url: uri+'/mysrc/collectTopic?id='+topicId,
            contentType:'application/json;charset=utf-8',//指定为json类型
            //数据格式是json串，商品信息
            //data:JSON.stringify(jsonData),
            // data:jsonData,
            success:function(data){//返回json结果
                console.log(data);
                if(data.code == 110 ) {
                	$.modal({
					    text: '未登录，是否登录？',
					    buttons: [
					        {
					          	text: '取消'
					        },
					        {
					          	text: '确定',
					          	onClick: function() {
					            	$.router.loadPage("./login.html");
					          	}
					        }
					    ]
					})
                } else {
                	thisDom.addClass('sel')
                }
            }
        });
	}

	function  getPublicKey() {
	  	$.ajax({
			type : "GET",
			url : uri + "common/publickey?ip=127.0.0.1",
			// data:JSON.stringify(loginData),
			contentType:"application/json;charset=UTF-8",  //发送至服务器的类型
			dataType : "json",     //预期服务器返回类型
			success: function(data){
				console.log(data);
				if(data.code == 0) {
					publicKey = data.object.data;
					var jbase = new JBase64();
					publicKey = jbase.decode(publicKey);
				} else {
					$.alert(data.messages)
				}
			}

	  	});
	}
	getPublicKey();

	function encryption(data , key){
	  	var encrypt = new JSEncrypt();
	  	if(null == key) {
	      	alert("Public Key not set");
	      	return ;
	  	}
		encrypt.setPublicKey(key);
		var md5Pass = hex_md5(data);
		var passwdEnc = encrypt.encrypt(md5Pass);

		return passwdEnc;
	}
	// 实时监听手机号码有没有输入
	$(document).bind('input propertychange', '.tels', function() {  
		// console.log($(this).parent(".boxs-input").siblings('.boxs-input:nth-child(2)').children('.yzm-btn'));
	   	if($(this).val() == "") {
	   		$(this).parent(".boxs-input").siblings('.boxs-input:nth-child(2)').children('.yzm-btn').addClass("sel");
	   	} else {
	   		$(this).parent(".boxs-input").siblings('.boxs-input:nth-child(2)').children('.yzm-btn').removeClass("sel");
	   	}
	}); 
	// 点击获取验证码
	$(document).on("click", ".yzm-btn", function() { 
		var thisBtn = $(this);
		if(!$(this).hasClass("sel")) {
			$(this).addClass("sel");
			var t = 3;
			
			$.ajax({
				type: 'POST',
				url: uri+'common/sendsms',
				data: { 
					phone: $("#tel").val()
				},
				dataType: 'json',
				success: function(data){
					console.log(data);
					if(data.code == 0) {
						timer = setInterval(function() {
							t --;
							thisBtn.html(t+" s重发");
							if(t <=0) {
								thisBtn.removeClass("sel");
								thisBtn.html("获取验证码");
								clearInterval(timer);
							}
						}, 1000);	
					} else {
						$.alert(data.messages)
					}
				},
				error: function(xhr, type){
					thisBtn.removeClass("sel");
					$.alert('请求失败');
				}
			})
		}
	}); 

	// 点击清空手机号 #
	$(document).on("click",".clear-all", function() { 
		$(this).siblings('input').val("");
		$(this).parent(".boxs-input").siblings('.boxs-input:nth-child(2)').children('.yzm-btn').addClass("sel");
	}); 
	// 显示密码框
	var clicked = true;
	$(document).on("click","#showPwd", function() { 
		if(clicked == true) {
			$("#loginPwd").attr("type", "text");
			clicked = false;
		} else {
			$("#loginPwd").attr("type", "password");
			clicked = true;
		}
	}); 
	// 点击注册
	$(document).on("click","#submit", function() { 
	    var loginData  = {
	        "nickname": $('#tel').val(),
	        "password": $('#loginPwd').val(),
	        "randomCode":$('#yzm').val(),
	        "phoneNo" : $('#tel').val(),
	    }; //发送给服务器的JSON

	    loginData.password =  encryption(loginData.password , publicKey);

	    $.ajax({
	        type : "POST",
	        url : uri+"/user/register",
	        data:JSON.stringify(loginData),
	        contentType:"application/json;charset=UTF-8",  //发送至服务器的类型
	        dataType : "json",     //预期服务器返回类型
	        success: function(data){
	        	if(data.code == 0) {
	            	$.router.load("#router"); 
	            } else {
					$.alert(data.messages)
				}
	        }

	    })
	})
	// 点击修改
	$(document).on("click","#modify", function() {
		var data = {
	        "nickname": $("#tel1").val(),
	        "phoneNo": $("#tel1").val(),
	        "password": $("#loginPwd1").val(),
	        "randomCode": $("#yzm1").val()
	    };
	    data.password =  encryption(data.password , publicKey);
	    $.ajax({
	        type : "POST",
	        url : uri+"user/resetpasswd",
	        data:JSON.stringify(data),
	        contentType:"application/json;charset=UTF-8",  //发送至服务器的类型
	        dataType : "json",     //预期服务器返回类型
	        success: function(data){
	        	if(data.code == 0) {
	            	$.router.load("#router"); 
	            } else {
					$.alert(data.messages)
				}
	        }

	    })
	})
	// 登陆
	$(document).on("click","#loginBtn", function() { 

		// pwdVal = encryption(pwdVal, publicKey);
		var loginData  = {
	      	"nickname": $("#user").val(),
	      	"password": $("#psw").val()

	    }; //发送给服务器的JSON
	  	loginData.password =  encryption(loginData.password , publicKey);
	  	console.log(loginData.password);

		$.ajax({
			type: 'POST',
			url: uri+'login',
			dataType: 'json',
			cache: true,
			contentType : "application/json; charset=utf-8",  
			data: JSON.stringify(loginData),
			success: function(data){
				console.log(data);
				if(data.code == 0) {
	            	$.router.loadPage('./index.html'); 
	            } else {
					$.alert(data.messages)
				}
			},
			error: function(xhr, type){
				alert('Ajax error!')
			}
		})
	})
	
 	$.init()//关键
})

